<template>
<div>
	<el-alert
		:title="notice"
		type="info"
		:show-icon="true"
		:closable="true"
		style="margin-bottom:5px">
	</el-alert>
	<el-select 
		v-model="currentvalue"
		@input='onInput'
		filterable
		allow-create
		>
		<el-option
		v-for="item in options"
		:key="item.value"
		:label="item.label"
		:value="item.value"
		>
		</el-option>
	</el-select>
	<i v-if="loading && !adding" class="el-icon-loading"></i>
	<el-button v-if="added" icon="plus" :loading="adding"  type="primary" @click="onAdd"></el-button>
	</div>
</template>
<script>
	import Vue from 'vue'
	import ElementUI from 'element-ui'
	import request from '../utils/axios'
	import utils from '../utils/utils'
	Vue.use(ElementUI);
	export default {
		name: 'wt-add-select',
		props: {
			field: {
				type: Object,
				required: true,
			},
			value: {
				type: [Number,String],
				default: ''
			}
		},
		data() {
			return {
				query: this.field.query,
				options: [],
				adding: false,
				loading: false,
				addingKeyword: '',
				added: false,
				currentvalue: this.value
			}
		},
		computed:{
			notice(){
				return '您可以从以下选项中选择或添加（输入内容后点击右边“+”号）相应类型'
			}
		},
		watch:{
			'currentvalue':function(val){
				this.$emit('input',val)
			}
		},
		methods:{
			getOptions(){
				request(this.query.url,this.query.method,this.query.param,this.query.transfer,(data)=>{
					let options = [];
					for(var i=0;i<data.length;i++){
						options.push({
							value:data[i].id,
							label:data[i].name
							})
					}
					this.options = options
				},function(error){
					this.$message.error('获取失败');
				},this.field.returnAllData)
			},
			onInput(val){
				let isexist = false
				for(let a=0;a<this.options.length;a++){
					if(val == this.options[a].value){
						isexist = true
					}
				}
				if(val!==''&&!isexist){
					this.added = true
				}else{
					this.added = false
				}
				this.addingKeyword = val
				this.currentvalue = val
			},
			onAdd(){
				let data = {};
				data[this.query.addParam] = this.addingKeyword;
				request(this.query.addurl,this.query.addMethod,data,this.query.transfer,(data)=>{
					this.options.push({
						value:data.id,
						label:data.name
					})
					this.currentvalue = data.id
					this.$message.success('添加数据成功');
					this.added = false
				},function(error){
					this.$message.error('添加数据失败，请稍候重试');
				},this.field.addReturnAllData)
			}
		},
		created(){
			this.getOptions()
		}
	}
</script>